package com.song.boot.springstudy.netty.idle;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 客户端心跳处理Handler
 */
class HeartbeatClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.WRITER_IDLE) {
                // 写空闲（即客户端没有发送数据），发送心跳包
                    ctx.writeAndFlush("PING");
                System.out.println("发送心跳PING到服务端");
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 收到心跳回复PONG
        if (msg instanceof String && "PONG".equals(msg)) {
            System.out.println("收到服务端心跳回复PONG");
        } else {
            super.channelRead(ctx, msg);
        }
    }
}